package com.pippin.editor.common;

import lombok.Data;
import org.springframework.validation.Errors;

import java.util.HashMap;
import java.util.stream.Collectors;

@Data
public class Res<T> {

    private Integer code = 0;

    private String message;

    private T data;

    public static Res<Object> OK() {
        return new Res<>();
    }

    public static <T> Res<T> OK(String msg) {
        Res<T> res = new Res<>();
        res.message = msg;
        return res;
    }

    public static <T> Res<T> OK(T data) {
        Res<T> res = new Res<>();
        res.data = data;
        return res;
    }

    public static <T> Res<T> OK(String msg, T data) {
        Res<T> res = new Res<>();
        res.message = msg;
        res.data = data;
        return res;
    }

    public static <T> Res<T> ERROR(Integer code, String msg, T data) {
        Res<T> res = new Res<>();
        res.code = code;
        res.message = msg;
        res.data = data;
        return res;
    }

    public static <T> Res<T> ERROR(String msg, T data) {
        Res<T> res = new Res<>();
        res.code = 500;
        res.message = msg;
        res.data = data;
        return res;
    }

    public static <T> Res<T> ERROR(Integer code, T data) {
        Res<T> res = new Res<>();
        res.code = 500;
        res.data = data;
        return res;
    }

    public static <T> Res<T> ERROR(String msg) {
        Res<T> res = new Res<>();
        res.code = 500;
        res.message = msg;
        return res;
    }

    public static Boolean CHECK_OK(Res<?> res) {
        return res.code == 0;
    }

    public static Res<String> ERROR(Errors errors){
        String errMsg = errors.getFieldErrors().stream().map(v -> {
            HashMap<String, Object> errMap = new HashMap<>();
            errMap.put(v.getField(), v.getDefaultMessage());
            return errMap.toString();
        }).collect(Collectors.joining());
        return Res.ERROR(errMsg);
    }


}
